const { getCaseKnex } = require('../database/knex');


const EntityResolutionService = require('./EntityResolutionService');
const RelationshipBuilder = require('./RelationshipBuilder');
const TimelineBuilder = require('./TimelineBuilder');

class ProfileEngine {
    /**
     * Build profile cache for a case
     * Scans raw data tables and aggregates into profile tables
     */
    static async buildProfileCache(caseId, dbPath) {
        const knex = getCaseKnex(caseId, dbPath);

        try {
            await knex.transaction(async (trx) => {
                // 1. Clear existing profile data (Full rebuild for now)
                console.log('[ProfileEngine] Step 1: Clearing existing profile data...');
                await trx('profile_entities').del();
                await trx('profile_relationships').del();
                await trx('profile_timeline').del();

                // 2. Entity Resolution
                console.log('[ProfileEngine] Step 2: Entity Resolution...');
                await EntityResolutionService.extractFromPersonalInfo(trx);
                await EntityResolutionService.extractFromBankTransactions(trx);
                await EntityResolutionService.extractFromCallRecords(trx);

                // 3. Relationship Building
                console.log('[ProfileEngine] Step 3: Relationship Building...');
                await RelationshipBuilder.buildBankRelationships(trx);
                await RelationshipBuilder.buildCallRelationships(trx);

                // 4. Timeline Building
                console.log('[ProfileEngine] Step 4: Timeline Building...');
                await TimelineBuilder.build(trx);

                console.log('[ProfileEngine] Profile build completed successfully.');
            });

            return { success: true };
        } catch (error) {
            console.error('Profile build failed:', error);
            throw error;
        }
    }

    /**
     * Get profile entities list
     */
    static async getEntities(caseId, dbPath) {
        const knex = getCaseKnex(caseId, dbPath);
        return await knex('profile_entities').select('*').limit(100);
    }

    /**
     * Get graph data
     */
    static async getGraphData(caseId, dbPath) {
        const knex = getCaseKnex(caseId, dbPath);

        const nodes = await knex('profile_entities').select('id', 'name', 'entity_type as type').limit(50);
        const edges = await knex('profile_relationships')
            .select('source_identifier as source', 'target_identifier as target', 'weight', 'relation_type')
            .orderBy('weight', 'desc')
            .limit(100);

        // Ensure all edge nodes exist in nodes list
        const nodeIds = new Set(nodes.map(n => n.id));
        const validEdges = edges.filter(e => nodeIds.has(e.source) || nodeIds.has(e.target)); // Relaxed for demo

        // Add missing nodes from edges if needed (simplified)

        return { nodes, edges: validEdges };
    }

    /**
     * Get timeline for an entity
     */
    static async getTimeline(caseId, dbPath, identifier) {
        const knex = getCaseKnex(caseId, dbPath);
        return await knex('profile_timeline')
            .where('identifier', identifier)
            .orderBy('event_time', 'desc')
            .limit(100);
    }
}

module.exports = ProfileEngine;
